{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-04-25T07:07:29.937496Z",
     "start_time": "2025-04-25T07:07:29.917255Z"
    }
   },
   "source": [
    "import torch\n",
    "from torch import nn\n",
    "from d2l import torch as d2l\n",
    "import utils.Utils as ut\n",
    "\n",
    "\n",
    "def dropout_layer(X, dropout):\n",
    "    assert 0 <= dropout <= 1\n",
    "    # 在本情况中，所有元素都被丢弃\n",
    "    if dropout == 1:\n",
    "        return torch.zeros_like(X)\n",
    "    # 在本情况中，所有元素都被保留\n",
    "    if dropout == 0:\n",
    "        return X\n",
    "    mask = (torch.rand(X.shape) > dropout).float()\n",
    "    return mask * X / (1.0 - dropout)"
   ],
   "outputs": [],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-25T07:07:29.969156Z",
     "start_time": "2025-04-25T07:07:29.954474Z"
    }
   },
   "cell_type": "code",
   "source": [
    "X= torch.arange(16, dtype = torch.float32).reshape((2, 8))\n",
    "print(X)\n",
    "print(dropout_layer(X, 0.))\n",
    "print(dropout_layer(X, 0.5))\n",
    "print(dropout_layer(X, 1.))"
   ],
   "id": "160f2075cff33a76",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.],\n",
      "        [ 8.,  9., 10., 11., 12., 13., 14., 15.]])\n",
      "tensor([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.],\n",
      "        [ 8.,  9., 10., 11., 12., 13., 14., 15.]])\n",
      "tensor([[ 0.,  2.,  0.,  0.,  0.,  0.,  0., 14.],\n",
      "        [16.,  0.,  0.,  0., 24., 26.,  0., 30.]])\n",
      "tensor([[0., 0., 0., 0., 0., 0., 0., 0.],\n",
      "        [0., 0., 0., 0., 0., 0., 0., 0.]])\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-25T07:07:30.000145Z",
     "start_time": "2025-04-25T07:07:29.985795Z"
    }
   },
   "cell_type": "code",
   "source": "num_inputs, num_outputs, num_hiddens1, num_hiddens2 = 784, 10, 256, 256",
   "id": "3d06d59644a2c875",
   "outputs": [],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-25T07:07:30.031184Z",
     "start_time": "2025-04-25T07:07:30.016916Z"
    }
   },
   "cell_type": "code",
   "source": [
    "dropout1, dropout2 = 0.2, 0.5\n",
    "\n",
    "class Net(nn.Module):\n",
    "    def __init__(self, num_inputs, num_outputs, num_hiddens1, num_hiddens2,\n",
    "                 is_training = True):\n",
    "        super(Net, self).__init__()\n",
    "        self.num_inputs = num_inputs\n",
    "        self.training = is_training\n",
    "        self.lin1 = nn.Linear(num_inputs, num_hiddens1)\n",
    "        self.lin2 = nn.Linear(num_hiddens1, num_hiddens2)\n",
    "        self.lin3 = nn.Linear(num_hiddens2, num_outputs)\n",
    "        self.relu = nn.ReLU()\n",
    "\n",
    "    def forward(self, X):\n",
    "        H1 = self.relu(self.lin1(X.reshape((-1, self.num_inputs))))\n",
    "        # 只有在训练模型时才使用dropout\n",
    "        if self.training == True:\n",
    "            # 在第一个全连接层之后添加一个dropout层\n",
    "            H1 = dropout_layer(H1, dropout1)\n",
    "        H2 = self.relu(self.lin2(H1))\n",
    "        if self.training == True:\n",
    "            # 在第二个全连接层之后添加一个dropout层\n",
    "            H2 = dropout_layer(H2, dropout2)\n",
    "        out = self.lin3(H2)\n",
    "        return out\n",
    "\n",
    "\n",
    "net = Net(num_inputs, num_outputs, num_hiddens1, num_hiddens2)"
   ],
   "id": "e820dab060b5052a",
   "outputs": [],
   "execution_count": 14
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "num_epochs, lr, batch_size = 10, 0.5, 256\n",
    "loss = nn.CrossEntropyLoss(reduction='none')\n",
    "train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)\n",
    "trainer = torch.optim.SGD(net.parameters(), lr=lr)\n",
    "ut.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)"
   ],
   "id": "fc24013404f7c3a5",
   "execution_count": 15,
   "outputs": []
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-25T07:08:35.791357Z",
     "start_time": "2025-04-25T07:08:35.775510Z"
    }
   },
   "cell_type": "code",
   "source": [
    "net = nn.Sequential(nn.Flatten(),\n",
    "        nn.Linear(784, 256),\n",
    "        nn.ReLU(),\n",
    "        # 在第一个全连接层之后添加一个dropout层\n",
    "        nn.Dropout(dropout1),\n",
    "        nn.Linear(256, 256),\n",
    "        nn.ReLU(),\n",
    "        # 在第二个全连接层之后添加一个dropout层\n",
    "        nn.Dropout(dropout2),\n",
    "        nn.Linear(256, 10))\n",
    "\n",
    "def init_weights(m):\n",
    "    if type(m) == nn.Linear:\n",
    "        nn.init.normal_(m.weight, std=0.01)\n",
    "\n",
    "net.apply(init_weights);"
   ],
   "id": "1e1ee53e035a1c53",
   "outputs": [],
   "execution_count": 16
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "trainer = torch.optim.SGD(net.parameters(), lr=lr)\n",
    "ut.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)"
   ],
   "id": "f6e6ba6c8a470e44",
   "execution_count": 18,
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
